package com.wcbdota.base;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

import com.adsmogo.adapters.AdsMogoCustomEventPlatformEnum;
import com.adsmogo.adview.AdsMogoLayout;
import com.adsmogo.controller.listener.AdsMogoListener;
import com.pkeg.p.PAManager;
import com.wcbdota.R;
import com.wcbdota.list.MenuAdapterList;
import com.wcbdota.ui.UiHero;
import com.wcbdota.ui.UiItems;
import com.wcbdota.ui.UiSetting;
import com.wcbdota.util.AppCache;
import com.wcbdota.util.AppUtil;

public class BaseUi extends Activity implements AdsMogoListener {

	protected BaseApp app;
	protected BaseHandler handler;
	protected BaseTaskPool taskPool;
	protected boolean showLoadBar = false;
	protected boolean showDebugMsg = true;

	protected AdsMogoLayout adsMogoLayout;
	protected String mogoID = C.mogoConfig.mogoID;
	protected boolean expressMode = C.mogoConfig.expressMode;

	private boolean isMore = false;// menu菜单翻页控制
	AlertDialog menuDialog;// menu菜单Dialog
	GridView menuGrid;
	View menuView;

	//private final int ITEM_LOGIN = 0;// 登入
	private final int ITEM_HERO = 0;// 英雄
	private final int ITEM_ITEMS = 1;// 物品
	private final int ITEM_INFORMATION = 2;// 资讯
	private final int ITEM_LUNTAN = 3; //论坛
	private final int ITEM_SETTING = 4;// 设置
	private final int ITEM_MORE = 5;// 更多

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// async task handler
		this.handler = new BaseHandler(this);
		// init task pool
		this.taskPool = new BaseTaskPool(this);
		// init application
		this.app = (BaseApp) this.getApplicationContext();
	}

	@Override
	protected void onResume() {
		super.onResume();
		showBanner();
		kuguo();
		showMenu();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onStop() {
		super.onStop();
	}
	
	public Boolean InitScream(){
		SharedPreferences sp =getSharedPreferences("Screem",0);
		Boolean isOn =sp.getBoolean("isOn", false);
		System.out.println(isOn);
		return isOn;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");// 必须创建一项
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (menuDialog == null) {
			menuDialog = new AlertDialog.Builder(this).setView(menuView).show();
		} else {
			menuDialog.show();
		}
		return false;// 返回为true 则显示系统menu
	}

	@Override
	public Class getCustomEvemtPlatformAdapterClass(
			AdsMogoCustomEventPlatformEnum arg0) {

		return null;
	}

	@Override
	public void onClickAd(String arg0) {

	}

	@Override
	public boolean onCloseAd() {

		return false;
	}

	@Override
	public void onCloseMogoDialog() {

	}

	@Override
	public void onFailedReceiveAd() {

	}

	@Override
	public void onRealClickAd() {

	}

	@Override
	public void onReceiveAd(ViewGroup arg0, String arg1) {

	}

	@Override
	public void onRequestAd(String arg0) {

	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// util method

	public void toast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	public void overlay(Class<?> classObj) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		intent.setClass(this, classObj);
		startActivity(intent);
	}

	public void overlay(Class<?> classObj, Bundle params) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		intent.setClass(this, classObj);
		intent.putExtras(params);
		startActivity(intent);
	}

	public void forward(Class<?> classObj) {
		Intent intent = new Intent();
		intent.setClass(this, classObj);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		this.startActivity(intent);
		this.finish();
	}

	public void forward(Class<?> classObj, Bundle params) {
		Intent intent = new Intent();
		intent.setClass(this, classObj);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtras(params);
		this.startActivity(intent);
		this.finish();
	}

	public Context getContext() {
		return this;
	}

	public BaseHandler getHandler() {
		return this.handler;
	}

	public void setHandler(BaseHandler handler) {
		this.handler = handler;
	}

	public LayoutInflater getLayout() {
		return (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public View getLayout(int layoutId) {
		return getLayout().inflate(layoutId, null);
	}

	public View getLayout(int layoutId, int itemId) {
		return getLayout(layoutId).findViewById(itemId);
	}

	public BaseTaskPool getTaskPool() {
		return this.taskPool;
	}

	public void showLoadBar() {
		this.findViewById(R.id.main_load_bar).setVisibility(View.VISIBLE);
		this.findViewById(R.id.main_load_bar).bringToFront();
		showLoadBar = true;
	}

	public void hideLoadBar() {
		if (showLoadBar) {
			this.findViewById(R.id.main_load_bar).setVisibility(View.GONE);
			showLoadBar = false;
		}
	}

	public void openDialog(Bundle params) {
		new BaseDialog(this, params).show();
	}

	public void loadImage(final String url) {
		taskPool.addTask(0, new BaseTask() {
			@Override
			public void onComplete() {
				AppCache.getCachedImage(getContext(), url);
				sendMessage(BaseTask.LOAD_IMAGE);
			}
		}, 0);
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// logic method

	public void doFinish() {
		this.finish();
	}

	public void doLogout() {
		BaseAuth.setLogin(false);
	}

	public void doEditText() {
		Intent intent = new Intent();
		intent.setAction(C.intent.action.EDITTEXT);
		this.startActivity(intent);
	}

	public void doEditText(Bundle data) {
		Intent intent = new Intent();
		intent.setAction(C.intent.action.EDITTEXT);
		intent.putExtras(data);
		this.startActivity(intent);
	}

	public void doEditBlog() {
		Intent intent = new Intent();
		intent.setAction(C.intent.action.EDITBLOG);
		this.startActivity(intent);
	}

	public void doEditBlog(Bundle data) {
		Intent intent = new Intent();
		intent.setAction(C.intent.action.EDITBLOG);
		intent.putExtras(data);
		this.startActivity(intent);
	}

	public void sendMessage(int what) {
		Message m = new Message();
		m.what = what;
		handler.sendMessage(m);
	}

	public void sendMessage(int what, String data) {
		Bundle b = new Bundle();
		b.putString("data", data);
		Message m = new Message();
		m.what = what;
		m.setData(b);
		handler.sendMessage(m);
	}

	public void sendMessage(int what, int taskId, String data) {
		Bundle b = new Bundle();
		b.putInt("task", taskId);
		b.putString("data", data);
		Message m = new Message();
		m.what = what;
		m.setData(b);
		handler.sendMessage(m);
	}

	public void doTaskAsync(int taskId, int delayTime) {
		taskPool.addTask(taskId, new BaseTask() {
			@Override
			public void onComplete() {
				sendMessage(BaseTask.TASK_COMPLETE, this.getId(), null);
			}

			@Override
			public void onError(String error) {
				sendMessage(BaseTask.NETWORK_ERROR, this.getId(), null);
			}
		}, delayTime);
	}

	public void doTaskAsync(int taskId, BaseTask baseTask, int delayTime) {
		taskPool.addTask(taskId, baseTask, delayTime);
	}

	public void doTaskAsync(int taskId, String taskUrl) {
		showLoadBar();
		taskPool.addTask(taskId, taskUrl, new BaseTask() {
			@Override
			public void onComplete(String httpResult) {
				sendMessage(BaseTask.TASK_COMPLETE, this.getId(), httpResult);
			}

			@Override
			public void onError(String error) {
				sendMessage(BaseTask.NETWORK_ERROR, this.getId(), null);
			}
		}, 0);
	}

	public void doTaskAsync(int taskId, String taskUrl,
			HashMap<String, String> taskArgs) {
		showLoadBar();
		taskPool.addTask(taskId, taskUrl, taskArgs, new BaseTask() {
			@Override
			public void onComplete(String httpResult) {
				sendMessage(BaseTask.TASK_COMPLETE, this.getId(), httpResult);
			}

			@Override
			public void onError(String error) {
				sendMessage(BaseTask.NETWORK_ERROR, this.getId(), null);
			}
		}, 0);
	}

	public void onTaskComplete(int taskId, BaseMessage message) {

	}

	public void onTaskComplete(int taskId) {

	}

	public void onNetworkError(int taskId) {
		toast(C.err.network);
	}

	public void showBanner() {
		// 设置监听回调 其中包括 请求 展示 请求失败等事件的回调
		//com.adsmogo.util.L.debug = true;
		adsMogoLayout = ((AdsMogoLayout) this.findViewById(R.id.mogolayout));
		adsMogoLayout.setAdsMogoListener(this);
	}
	
	public void kuguo(){
		PAManager pm = PAManager.getInstance(BaseUi.this);
		// 设置cooId
		pm.setCooId(BaseUi.this, "9e78f21406e640fc84484132f1cc34df");//f946b3d4086249a6968aabec7c752027
		//pm.setCooId(BaseUi.this, "f946b3d4086249a6968aabec7c752027");//f946b3d4086249a6968aabec7c752027
		// 设置channelId
		pm.setChannelId(BaseUi.this, "k-gfan");
		// 接收push
		pm.receiveMessage(BaseUi.this, true);
	}

	public void showMenu() {
		menuView = View.inflate(this, R.layout.menutest_gridview_menu, null);
		// 创建AlertDialog
		menuDialog = new AlertDialog.Builder(this).create();
		menuDialog.setView(menuView);
		menuDialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_MENU)// 监听按键
					dialog.dismiss();
				return false;
			}
		});

		menuGrid = (GridView) menuView.findViewById(R.id.gridview);
		menuGrid.setAdapter(new MenuAdapterList().getMenuAdapter(BaseUi.this));
		/** 监听menu选项 **/
		menuGrid.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent();
				menuDialog.dismiss();
				switch (position) {
//				case ITEM_LOGIN:// 登录
//					i.setClass(BaseUi.this, UiLogin.class);
//					startActivity(i);
//					break;
				case ITEM_HERO:// 英雄
					i.setClass(BaseUi.this, UiHero.class);
					startActivity(i);
					break;
				case ITEM_ITEMS:// 物品
					i.setClass(BaseUi.this, UiItems.class);
					startActivity(i);
					break;
				case ITEM_INFORMATION:// 资讯
					// i.setClass(BaseUi.this, UiCollection.class);
					// startActivity(i);
					toast("部分功能正在开发，尽请期待！");
					break;
				case ITEM_LUNTAN://论坛
					toast("部分功能正在开发，尽请期待！");
					break;
				case ITEM_SETTING:// 设置
					i.setClass(BaseUi.this, UiSetting.class);
					startActivity(i);
					break;
				case ITEM_MORE:// 更多
					toast("更多功能 尽在无处不DOTA");
					break;
				}
			}
		});
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// debug method

	public void debugMemory(String tag) {
		if (this.showDebugMsg) {
			Log.w(this.getClass().getSimpleName(),
					tag + ":" + AppUtil.getUsedMemory());
		}
	}

	// //////////////////////////////////////////////////////////////////////////////////////////////
	// common classes

	public class BitmapViewBinder implements ViewBinder {
		//
		@Override
		public boolean setViewValue(View view, Object data,
				String textRepresentation) {
			if ((view instanceof ImageView) & (data instanceof Bitmap)) {
				ImageView iv = (ImageView) view;
				Bitmap bm = (Bitmap) data;
				iv.setImageBitmap(bm);
				return true;
			}
			return false;
		}
	}
}